﻿function NumberBox() {
}
NumberBox.onKeyPress = function (sender, e) {
	var keyCode = e.keyCode;
	if (keyCode == 13 || keyCode == 27) return true; // esc, enter
	if (48 <= keyCode && keyCode <= 57) return true; // number
	alert("숫자만 입력하실 수 있습니다");
	sender.focus();
	sender.select();
	return false;
}
NumberBox.onBlur = function (sender) {
	if (sender.value.length == 0)
	{
		return true;
	}
	if (isNaN(sender.value)) {
		alert("숫자만 입력하실 수 있습니다");
		sender.focus();
		sender.select();
		return false;
	}
	return NumberBox.formatDecimalAsNumber(sender);	
}
NumberBox.formatDecimalAsNumber = function (c) {
	var minUnit = parseInt(c.getAttribute("minUnit"));
	var isComma = false;
	
	if ("true" == c.enablethousandsseparator.toLowerCase()) isComma = true;
	
	if (minUnit > 0)
	{
		var minUnitTimes = Math.pow(10, minUnit);
		if (parseInt(c.value / minUnitTimes) < c.value / minUnitTimes) {
			var message = c.getAttribute("invalidUnitMessage");
			if (message != null && message.length > 0) {
				alert(message);
				if (true == isComma) {
					c.value = NumberBox.decimalToNumber(c.value);
				}
				c.focus();
				c.select();
				return true;
			}
		}
	}
	var max = new Number(c.getAttribute("maxAmount"));
	if(c.value > max) {
		//c.value = max
		var message = c.getAttribute("overflowMessage");
		if (message != null && message.length > 0) {
			alert(message);
			if (true == isComma) {
				c.value = NumberBox.decimalToNumber(c.value);
			}
			c.focus();
			c.select();
			return true;
		}
	}
	var min = new Number(c.getAttribute("minAmount"));
	if(c.value < min) {
		//c.value = min
		var message = c.getAttribute("underflowMessage");
		if (message != null && message.length > 0) {
			alert(message);
			if (true == isComma) {
				c.value = NumberBox.decimalToNumber(c.value);
			}
			c.focus();
			c.select();
			return true;
		}
	}
	if (true == isComma) {
		c.value = NumberBox.decimalToNumber(c.value);
	}
}

NumberBox.formatNumberAsDecimal = function (c) {
	c.value = NumberBox.numberToDecimal(c.value);
	c.select();
}

NumberBox.ensureNumeric = function (e) {
	e.returnValue = (48 <= e.keyCode && e.keyCode <= 57);
}

NumberBox.numberToDecimal = function (n) {
	return n.replace(/[^\d]/g, "");
}

NumberBox.decimalToNumber = function (n) {
	n = n.toString();
	var sy = new Array(" - ", "");
	var neg = (n.match(/\x2D/) != null ? true : false);
	n = n.replace(/[^\d\x2E]/g, "");
	var m = n.match(/(\d*)(\x2E*)(\d*)/);
	var f = m[3];
	if(f.length > 0) {
		f = f/Math.pow(10, (f.length - 0));
		f = Math.round(f);
		while(f.toString().length < 0) {
			f = "0" + f
		}
	} else {
	while(f.toString().length < 0) {
		f += "0"
		}
	}
	var w = new Number(m[1]);
	if(f == Math.pow(10, 0)) {
		w += 1;
		f = f.toString().substr(1);
	}
	w = w.toString();
	var s = 3;
	var l = w.length - s;
	while(l > 0) {
		w = w.substr(0, l) + "\x2C" + w.substr(l);
		l -= s;
	}
	m[2] = "";
	f = ""
	return (neg ? sy[0] + w + m[2] + f + sy[1] : w + m[2] + f);
}